package cn.yangliu.task.socket;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.InitializingBean;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * 作者 杨柳
 * 时间 2017-09-25 10:18
 * 描述
 */
public class TaskSocketClient implements InitializingBean {

    private int port;
    private String host;
    private DatagramSocket socket;

    private InetAddress address = null;

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public synchronized String send(SocketInfo info) {
        try {
              /*
         * 作为向服务器端发送数据
         */
            String content = JSON.toJSONString(info);
            byte[] sendData = content.getBytes();
            // 创建数据报，包含发送的数据信息
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, address, port);
            // 向服务器端发送数据报
            socket.send(sendPacket);

            //===============================================================================================
        /*
         * 接收服务端发送的数据
         */
            // 创建数据报，用于接收客户端发送的数据
            byte[] data = new byte[10240];// 创建字节数组，指定接收的数据包的大小
            DatagramPacket recivePacket = new DatagramPacket(data, data.length);
            // 接收客户端发送的数据
            socket.receive(recivePacket);// 此方法在接收到数据报之前会一直阻塞
            return new String(data, 0, recivePacket.getLength());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public void afterPropertiesSet() throws Exception {
        // 定义服务器的地址、端口号、数据
        address = InetAddress.getByName(host);
        // 创建DatagramSocket对象
        socket = new DatagramSocket();
    }
}
